package cn.wenhaha.app.job;

import cn.hutool.core.lang.JarClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * 同步类加载
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-11-14 20:04
 */

public class SyncClassLoader extends URLClassLoader {

    private final Logger logger = LoggerFactory.getLogger(SyncClassLoader.class);



    private SyncClassLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
    }

    public static  SyncClassLoaderBuilder builder(){
        return  new SyncClassLoaderBuilder();
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> aClass = super.findClass(name);

        logger.debug("通过同步类加载器---> "+aClass.getName() +"@@@"+ aClass.getClassLoader());

        return aClass;
    }

    public  static class  SyncClassLoaderBuilder{
        private ArrayList<URL> list=new ArrayList<>(0);

        public SyncClassLoaderBuilder add(JarClassLoader loader){
            URL[] urLs = loader.getURLs();
            list.addAll(Arrays.asList(urLs));
            return  this;
        }

        public SyncClassLoader build(){
            return   new SyncClassLoader(list.toArray(new URL[]{}),Thread.currentThread().getContextClassLoader());
        }

    }



}
